package core;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GameManager {
    private final List<Board> games;
    private static int currentGameIndex;
    private final Scanner scanner;

    public GameManager() {
        games = new ArrayList<>();
        scanner = new Scanner(System.in);

        // 初始三局游戏，一局peace，一局reversi，一句gomoku
        games.add(new PeaceBoard("Player1", "Player2"));
        games.add(new ReversiBoard("Player1", "Player2"));
        games.add(new Five_keyBoard("Player1", "Player2"));
        currentGameIndex = 0;
    }

    public static int getCurrentGameIndex() {
        return currentGameIndex;
    }

    public void start() {
        while (true) {
            clearScreen();
            displayCurrentGame();

            System.out.println("请玩家[" + getCurrentGame().getCurrentPlayer().getName() + "]输入落子位置(如1A) / " +
                    "游戏编号(1-" + games.size() + ") / " +
                    "新游戏类型(peace/reversi/gomoku) / " +
                    "放弃行棋(pass) / " +
                    "退出程序(quit):");

            String input = scanner.nextLine().trim().toLowerCase();

            if (input.equals("quit")) {
                System.out.println("游戏结束，谢谢游玩！");
                break;
            } else if (input.equals("pass")) {
                handlePass();
            } else if (input.equals("peace") || input.equals("reversi") || input.equals("gomoku")) {
                addNewGame(input);
            } else if (isValidGameNumber(input)) {
                switchGame(input);
            } else {
                handleMove(input);
            }
        }
    }

    private void handlePass() {
        Board currentGame = getCurrentGame();
        if (currentGame instanceof ReversiBoard) {
            ((ReversiBoard) currentGame).pass();
        } else {
            System.out.println("当前游戏模式不支持pass操作！");
            waitForEnter();
        }
    }

    private void addNewGame(String gameType) {
        String player1 = "Player1";
        String player2 = "Player2";

        switch (gameType) {
            case "peace" -> games.add(new PeaceBoard(player1, player2));
            case "reversi" -> games.add(new ReversiBoard(player1, player2));
            case "gomoku" -> games.add(new Five_keyBoard(player1, player2));
        }
        System.out.println("已添加新的" + gameType + "游戏，编号为" + games.size());
        waitForEnter();
    }

    private void switchGame(String input) {
        int gameNumber = Integer.parseInt(input);
        if (gameNumber >= 1 && gameNumber <= games.size()) {
            currentGameIndex = gameNumber - 1;
        } else {
            System.out.println("无效的游戏编号！");
            waitForEnter();
        }
    }

    private void handleMove(String input) {
        try {
            if (input.length() == 2) {
                int row = Integer.parseInt(input.substring(0, 1)) - 1;
                char colChar = input.charAt(1);
                int col = colChar - 'a';

                if (row >= 0 && row < 8 && col >= 0 && col < 8) {
                    boolean moveResult = getCurrentGame().makeMove(row, col);
                    if (!moveResult) {
                        System.out.println("非法落子位置！");
                        waitForEnter();
                    }
                } else {
                    System.out.println("坐标超出范围！");
                    waitForEnter();
                }
            } else {
                System.out.println("输入格式错误！");
                waitForEnter();
            }
        } catch (NumberFormatException e) {
            System.out.println("输入格式错误！");
            waitForEnter();
        }
    }

    private boolean isValidGameNumber(String input) {
        try {
            int gameNumber = Integer.parseInt(input);
            return gameNumber >= 1 && gameNumber <= games.size();
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public Board getCurrentGame() {
        return games.get(currentGameIndex);
    }

    private void displayCurrentGame() {
        getCurrentGame().display();

        System.out.println("\n游戏列表:");
        String type = "";
        for (int i = 0; i < games.size(); i++) {
            if (games.get(i) instanceof PeaceBoard) {
                type = "peace";
            } else if (games.get(i) instanceof ReversiBoard) {
                type = "reversi";
            } else if (games.get(i) instanceof Five_keyBoard) {
                type = "gomoku";
            }

            System.out.println((i + 1) + ". " + type +
                    (i == currentGameIndex ? " (当前)" : ""));
        }
    }

    private void clearScreen() {
        try {
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        } catch (Exception e) {

            for (int i = 0; i < 50; i++)
                System.out.println();
        }
    }

    private void waitForEnter() {
        System.out.println("按回车键继续...");
        scanner.nextLine();
    }
}